# -*- encoding: utf-8 -*-
"""
App级的调用外部接口共通方法
"""

import json
import ssl

from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPError

from common import logtool, config
import settings


@gen.coroutine
def get_request_data(request_handler, request_url, ret_type='dict'):
    """
    通过指定的url来获取数据
    :param request_handler: 请求数据的request_handler
    :param request_url: 请求数据的url
    :param ret_type:  返回的数据格式 如 'dict' | 'list'
    :return: 获取请求的数据
    """
    print 'IN URL: ', request_url

    client = AsyncHTTPClient()

    try:
        context = None
        if request_url.split(':', 1)[0] == "https":
            context = ssl._create_unverified_context()
        response = yield client.fetch(
            request_url,
            headers={'Content-Type': 'application/json', 'Accept': 'application/json'})
        res = json.loads(response.body)
    except HTTPError,ex:
        print 'Error: ', ex
        logtool.save_error_log(msg_type=settings.MSG_TYPE, interface=request_handler.request.uri,
                               server_ip=settings.SERVER_IP, memo=request_url, project_path=settings.PROJECT_PATH)
        if ret_type == 'dict':
            res = {'code': '1003', 'msg': config.CODE1047}
        elif ret_type == 'list':
            res = {'code': '1003', 'msg': config.CODE1047, 'info': []}

    raise gen.Return(res)
